<template>
  <div class="dashboard-container">
    <panel-group @handleSetLineChartData="handleSetLineChartData" />
    <!-- 图表区域 -->
    <el-row :gutter="15" class="mb-4">
      <!-- 用户增长趋势 -->
      <el-col :span="16" :xs="24">
        <el-card
          shadow="hover"
          style="border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1)"
        >
          <div slot="header" class="chart-header chart-header-title">
            <span>用户增长趋势</span>
          </div>
          <div
            class="chart-container"
            style="
              height: 290px;
              margin-top: 5px;
              background: #f8fafc;
              border-radius: 8px;
              padding: 16px;
            "
          >
            <canvas id="userGrowthChart"></canvas>
          </div>
        </el-card>
      </el-col>

      <!-- 快捷操作 -->
      <el-col :span="8">
        <el-card
          shadow="hover"
          style="border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1)"
        >
          <div slot="header" class="actions-header chart-header-title">
            <span>快捷操作入口</span>
          </div>
          <el-row :gutter="10">
            <el-col
              :span="12"
              v-for="(action, index) in quickActions"
              :key="index"
              style="margin-bottom: 10px"
            >
              <el-button
                class="action-btn"
                :class="action.class"
                @click="handleAction(action)"
                :disabled="action.link === '--'"
                style="
                  width: 100%;
                  height: 88px;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  border-radius: 8px;
                  transition: all 0.3s;
                "
              >
                <router-link :to="action.link">
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <template v-if="action.icon.startsWith('el-')">
                      <i
                        :class="action.icon"
                        class="action-icon"
                        style="font-size: 24px; margin-bottom: 6px"
                      ></i>
                    </template>
                    <template v-else>
                      <svg-icon
                        :icon-class="action.icon"
                        style="width: 28px; height: 28px; margin-bottom: 6px"
                      />
                    </template>
                    <span
                      class="action-text"
                      style="font-size: 14px; text-align: center"
                      >{{ action.name }}</span
                    >
                  </div>
                </router-link>
              </el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近记录和快捷操作 -->
    <el-row :gutter="15" class="mb-4">
      <!-- 最近体重记录 -->
      <el-col :span="16" :xs="24">
        <el-card
          shadow="hover"
          style="border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1)"
        >
          <div slot="header" class="record-header chart-header-title">
            <span>最近用户</span>
            <el-button type="text" size="mini" @click="viewAllRecords" round
              >查看全部</el-button
            >
          </div>
          <el-table
            :data="weightRecordsList"
            border
            stripe
            style="width: 100%"
            highlight-current-row
          >
            <el-table-column prop="user" label="用户" width="180">
              <template slot-scope="scope">
                <el-avatar
                  :src="scope.row.avatar"
                  class="user-avatar"
                ></el-avatar>
                <span class="user-name">{{ scope.row.user }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="记录时间"></el-table-column>
            <el-table-column prop="weight" label="体重(kg)"></el-table-column>
            <el-table-column prop="change" label="变化">
              <template slot-scope="scope">
                <span
                  :class="
                    scope.row.changeType === 'up' ? 'text-green' : 'text-red'
                  "
                >
                  <i
                    :class="
                      scope.row.changeType === 'up'
                        ? 'el-icon-caret-down'
                        : 'el-icon-caret-up'
                    "
                  ></i>
                  {{ scope.row.change }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status === '健康' ? 'success' : 'warning'"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 健康数据分布 -->
      <el-col :span="8" :xs="24">
        <el-card
          shadow="hover"
          style="border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1)"
        >
          <div slot="header" class="chart-header chart-header-title">
            <span>用户年龄分布</span>
            <el-button
              type="text"
              size="mini"
              @click="viewAllRecords"
              round
              icon="el-icon-refresh"
              >刷新</el-button
            >
          </div>
          <div class="chart-container pie-chart">
            <canvas id="healthDataChart"></canvas>
          </div>
          <el-row
            :gutter="10"
            type="flex"
            justify="center"
            class="chart-legend"
          >
            <el-col :span="7">
              <div class="legend-item">
                <span class="legend-color blue"></span>
                <span class="legend-text">体重</span>
              </div>
            </el-col>
            <el-col :span="7">
              <div class="legend-item">
                <span class="legend-color green"></span>
                <span class="legend-text">运动</span>
              </div>
            </el-col>
            <el-col :span="7">
              <div class="legend-item">
                <span class="legend-color purple"></span>
                <span class="legend-text">饮食</span>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Chart from "chart.js"; // 使用Chart.js v2版本的导入方式
import PanelGroup from "./dashboard/PanelGroup";
import { dashboardStats } from "../api/miniapp/wxAppDashboard.js";

export default {
  name: "Dashboard",
  components: {
    PanelGroup,
  },
  data() {
    return {
      // 日期范围
      dateRange: "week",
      selectedDate: "",
      chartRange: "month",

      // 模拟数据
      totalUsers: 12580,
      activeUsers: 7845,
      weightRecords: 45210,
      exerciseRecords: 32680,

      // 体重记录列表
      weightRecordsList: [
        {
          user: "张三",
          avatar: "https://picsum.photos/id/1005/40/40",
          time: "今天 08:30",
          weight: "72.5",
          change: "0.8kg",
          changeType: "up",
          status: "健康",
        },
      ],

      // 快捷操作
      quickActions: [
        {
          name: "小程序设置",
          icon: "system",
          class: "blue-btn",
          link: "/miniapp/miniapp",
        },
        {
          name: "用户管理",
          icon: "peoples",
          class: "green-btn",
          link: "/miniapp/miniAppUser",
        },
        {
          name: "运动分类",
          icon: "category",
          class: "purple-btn",
          link: "/miniapp/category",
        },
        {
          name: "运动项目",
          icon: "sports",
          class: "orange-btn",
          link: "/miniapp/sport",
        },
        {
          name: "个人中心",
          icon: "users",
          class: "red-btn",
          link: "/user/profile",
        },
        {
          name: "饮食监测",
          icon: "food",
          class: "gray-btn",
          link: "/food/index",
        },
      ],

      // 图表实例
      userGrowthChart: null,
      healthDataChart: null,
    };
  },
  created() {
    this.getStats();
  },
  mounted() {
    // 组件挂载时初始化图表
    this.initCharts();
  },
  beforeDestroy() {
    // 组件销毁前销毁图表
    this.destroyCharts();
  },
  methods: {
    getStats() {
      dashboardStats().then((res) => {
        console.log("获取数据成功:", res);
      });
    },
    handleSetLineChartData(type) {
      this.lineChartData = lineChartData[type];
    },

    // 查看全部记录
    viewAllRecords() {
      console.log("查看全部记录");
    },

    // 处理快捷操作
    handleAction(action) {
      if (action.link === "--") {
        return;
      }
      console.log("执行操作:", actionName.name);
      // 这里可以根据不同操作跳转到对应页面
    },

    // 刷新数据
    refreshData() {
      // 模拟数据刷新效果
      this.totalUsers += Math.floor(Math.random() * 100);
      this.activeUsers += Math.floor(Math.random() * 50);
      this.weightRecords += Math.floor(Math.random() * 200);
      this.exerciseRecords += Math.floor(Math.random() * 150);

      // 重新绘制图表
      this.destroyCharts();
      this.initCharts();
    },

    // 销毁图表
    destroyCharts() {
      if (this.userGrowthChart) {
        this.userGrowthChart.destroy();
      }
      if (this.healthDataChart) {
        this.healthDataChart.destroy();
      }
    },

    // 初始化图表
    initCharts() {
      // 用户增长趋势图
      const userGrowthCtx = document
        .getElementById("userGrowthChart")
        .getContext("2d");
      this.userGrowthChart = new Chart(userGrowthCtx, {
        type: "line",
        data: {
          labels: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          datasets: [
            {
              label: "新增用户",
              data: [
                650, 780, 920, 1050, 1200, 1450, 1600, 1850, 2100, 2350, 2600,
                2900,
              ],
              borderColor: "#409EFF",
              backgroundColor: "rgba(64, 158, 255, 0.1)",
              tension: 0.4,
              fill: true,
            },
            {
              label: "活跃用户",
              data: [
                420, 510, 630, 720, 850, 980, 1100, 1250, 1400, 1600, 1800,
                2000,
              ],
              borderColor: "#67C23A",
              backgroundColor: "rgba(103, 194, 58, 0.1)",
              tension: 0.4,
              fill: true,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          legend: {
            // Vue2使用的Chart.js v2版本中，legend是顶级配置，不是在plugins里
            position: "top",
            labels: {
              usePointStyle: true,
              boxWidth: 6,
            },
          },
          tooltips: {
            // v2版本中是tooltips，不是tooltip
            mode: "index",
            intersect: false,
          },
          scales: {
            xAxes: [
              {
                // v2版本中是xAxes数组
                grid: {
                  display: false,
                },
              },
            ],
            yAxes: [
              {
                // v2版本中是yAxes数组
                beginAtZero: true,
                grid: {
                  borderDash: [2, 4],
                  color: "rgba(0, 0, 0, 0.05)",
                },
              },
            ],
          },
          interaction: {
            mode: "nearest",
            axis: "x",
            intersect: false,
          },
          animation: {
            duration: 1000,
            easing: "easeOutQuart",
          },
        },
      });

      // 健康数据分布图
      const healthDataCtx = document
        .getElementById("healthDataChart")
        .getContext("2d");
      this.healthDataChart = new Chart(healthDataCtx, {
        type: "doughnut",
        data: {
          labels: ["体重记录", "运动记录", "饮食记录"],
          datasets: [
            {
              data: [45, 30, 25],
              backgroundColor: [
                "#409EFF", // Element UI 主色
                "#67C23A", // Element UI 成功色
                "#909399", // Element UI 常规色
              ],
              borderWidth: 0,
              hoverOffset: 4,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          cutout: "70%",
          legend: {
            // v2版本中是顶级配置
            display: false,
          },
          tooltips: {
            // v2版本中是tooltips
            callbacks: {
              label: function (context) {
                return `${context.label}: ${context.raw}%`;
              },
            },
          },
          animation: {
            animateRotate: true,
            animateScale: true,
            duration: 1000,
            easing: "easeOutQuart",
          },
        },
      });
    },
  },
};
</script>

<style scoped>
.mb-4 {
  margin-bottom: 15px;
}

.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 统计卡片样式 */
.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.stat-avatar {
  width: 40px;
  height: 40px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
  color: #303133;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.stat-trend.up {
  color: #67c23a;
}

.stat-trend.down {
  color: #f56c6c;
}

.stat-trend i {
  margin-right: 4px;
}

.chart-header-title {
  padding: 5px 15px;
  font-size: 14px;
  font-weight: 500;
}
/* 图表样式 */
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 300px;
  position: relative;
}

.pie-chart {
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-legend {
  margin-top: 15px;
  text-align: center;
}

.legend-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
  display: inline-block;
}

.legend-text {
  font-size: 12px;
  color: #606266;
}

/* 记录表格样式 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-avatar {
  width: 36px;
  height: 36px;
  margin-right: 10px;
  vertical-align: middle;
}

.user-name {
  vertical-align: middle;
}

.text-green {
  color: #67c23a;
}

.text-red {
  color: #f56c6c;
}

/* 快捷操作样式 */
.actions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-btn {
  width: 100%;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.action-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.action-text {
  font-size: 14px;
}

/* 颜色样式 */
.blue-avatar {
  background-color: #e6f7ff;
  color: #1890ff;
}

.green-avatar {
  background-color: #f0f9eb;
  color: #52c41a;
}

.purple-avatar {
  background-color: #f9f0ff;
  color: #722ed1;
}

.orange-avatar {
  background-color: #fff7e6;
  color: #faad14;
}

.blue {
  background-color: #409eff;
}

.green {
  background-color: #67c23a;
}

.purple {
  background-color: #909399;
}

.blue-btn {
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #b3d8ff;
}

.green-btn {
  background-color: #f0f9eb;
  color: #67c23a;
  border-color: #b7eb8f;
}

.purple-btn {
  background-color: #f9f0ff;
  color: #9370db;
  border-color: #e6a23c;
}

.orange-btn {
  background-color: #fff7e6;
  color: #e6a23c;
  border-color: #ffd666;
}

.red-btn {
  background-color: #fff2f3;
  color: #f56c6c;
  border-color: #ffb4b9;
}

.gray-btn {
  background-color: #f2f3f5;
  color: #909399;
  border-color: #dcdfe6;
}

/* 按钮激活状态 */
.is-active {
  color: #409eff;
  font-weight: bold;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chart-container {
    height: 220px;
  }

  .action-btn {
    height: 80px;
  }

  .action-icon {
    font-size: 20px;
  }

  .action-text {
    font-size: 12px;
  }
}
</style>
